#include "turret.h"
#include "linked.h"
#include "stats.h"

void init_turret(void)
{
	DDRM = 0xFF;
	current = cycle; 
	PTM = current->val;//0x05;       // activate turret, slow mode
}
void fire_turret(unsigned short distance)
{
	unsigned short out = distance/FACTOR;
	
	if(out > 400)
		out = 400;
	else if(out == 0)
		out = 1;
	
	sci_out_char(200);
}

void rotate_turret_half(signed short direction)
{
	if(direction < 0)
	{
		current = current->next;
		PTM = (PTM&0xF0)|current->val;
	}
	else if(direction > 0)
	{
		current = current->prev;
	  PTM = (PTM&0xF0)|current->val;
	}
}

void rotate_turret_full(signed short direction)
{
	if(direction < 0)
	{
		current = ((current-cycle)/sizeof(struct LinkedStruct)%2)==0?current->next->next:current->next;
		PTM = (PTM&0xF0)|current->val;
	}
	else if(direction > 0)
	{
		current = ((current-cycle)/sizeof(struct LinkedStruct)%2)==0?current->prev->prev:current->prev;
		PTM = (PTM&0xF0)|current->val;                      
	}
}

void set_turret_pos(unsigned short pos)
{
   unsigned short cur_pos = get_turret_heading();
   while(cur_pos - pos > 15 && cur_pos - pos < -15)
   {                                              
     rotate_turret_half(pos-cur_pos<0?(cur_pos-pos>512?(-(1024-cur_pos+pos)):(cur_pos-pos)):(pos-cur_pos>512?(-(1024-pos-cur_pos)):(pos-cur_pos)));
     cur_pos = get_turret_heading();
   }
   
}
